package org.budo.support.javax.servlet.http.util;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lmw
 */
public class CookieUtil {
    public static List<String> getCookieValue(Cookie[] cookies, String name) {
        if (null == cookies || null == name) {
            return null;
        }

        List<String> values = new ArrayList<String>();

        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(name)) {
                values.add(cookie.getValue());
            }
        }

        return values;
    }

    /**
     * 移除指定 cookie
     */
    public static void removeCookie(HttpServletResponse response, String name) {
        Cookie cookie = new Cookie(name, null);
        cookie.setHttpOnly(true);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

    /**
     * 移除所有 cookie
     */
    public static void removeCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            removeCookie(response, cookie.getName());
        }
    }
}
